<template>
  <div class="scaner" ref="scaner">
    <van-nav-bar
      title="扫一扫"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      style="background-color: #081c33;"
    />
    <div class="cover">
      <p class="line"></p>
      <span class="square top left"></span>
      <span class="square top right"></span>
      <span class="square bottom right"></span>
      <span class="square bottom left"></span>
      <p class="tips">将条形码放入框内，即可自动扫描</p>
    </div>
   <div 
      class="source"
      ref="video"
      id="video"
></div>
  </div>
</template>

<script>
import Quagga from 'quagga';
import { userStore } from "../../stores/user.ts";
import { ElMessageBox, ElMessage } from "element-plus";
import axios from 'axios'; // 确保引入axios

export default {
  name: 'scaner',
  props: {
    // 使用后置相机
    useBackCamera: {
      type: Boolean,
      default: true,
    },
    // 扫描识别后停止
    stopOnScaned: {
      type: Boolean,
      default: true,
    },
    drawOnfound: {
      type: Boolean,
      default: true,
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: "red",
    },
    // 线条宽度
    lineWidth: {
      type: Number,
      default: 2,
    },
    // 视频宽度
    videoWidth: {
      type: Number,
      default: window.innerWidth,
    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: window.innerHeight,
    },
    responsive: {
      type: Boolean,
      default: false,
    },
  },
   computed: {
    videoWH() {
      return { width: this.videoWidth, height: this.videoHeight };
    },
  },
  data() {
    return {
      scannedCode: null,
      decodedContent: null,
      videoStream: null,
      boundingBox: null, // 新增属性
      showPlay: false,
      showBanner: true,
      opacity: 0,
      User_Code: null,
      Interface_Code: null,
      user: null,
      t1: null,
      t2: null,
      t3: null,
      t4: null,
      ts4: null,
      sx: null
    };
  },
  mounted() {
      this.user = userStore();
    this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    this.Interface_Code = sessionStorage.getItem("item");
    this.initQuagga();
  },
  created() {
    // this.user = userStore();
    // this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    // this.Interface_Code = sessionStorage.getItem("item");
  },
  methods: {
    initQuagga() {
      Quagga.init({
        inputStream: {
          name: "Live",
          type: "LiveStream",
          target: document.querySelector("#video"),
          constraints: {
            facingMode: "environment", // 使用后置摄像头
             width: { min: 640},
              height: { min:480},
              frameRate: 600,
              focusMode: "continuous",
              focusDistance: { exact: 10000 },
          },
          area: {
            top: "10%",
            right: "10%",
            left: "10%",
            bottom: "10%"
          },
          singleChannel: false
        },
        decoder: {
          readers: ["code_128_reader", "ean_reader", "ean_8_reader", "upc_reader", "upc_e_reader"]
        }
      }, (err) => {
        if (err) {
          console.error("Error initializing Quagga:", err);
          ElMessage.error("无法初始化扫描器，请检查摄像头权限或设备设置。");
          return;
        }
        console.log("QuaggaJS initialized and ready.");
        Quagga.start();
      });

      Quagga.onDetected(this.onDetected);
    },
    onDetected(result) {
      this.scannedCode = result.codeResult.code;
      console.log("Barcode detected and processed : ", result.codeResult.code);
      if (this.scannedCode.length === 10) {
        Quagga.stop();
        axios
          .post(
            window.globalUrl.server + "Service.asmx/Get_CheckSub_Data",
            JSON.stringify({
              User_Code: this.User_Code,
              Interface_Code: this.Interface_Code,
              Check_No: result.codeResult.code,
            }),
          )
          .then((res) => {
            if (res.data.RltCode == 1) {
              this.user.Get_CheckSub_Data1 = JSON.parse(res.data.RltData);
              sessionStorage.setItem(
                "data1",
                JSON.stringify(JSON.parse(res.data.RltData))
              );
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/Get_ZytzEndInfo",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data1.Pson_CardID,
                  }),
                
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    this.user.Tz_End = JSON.parse(res.data.RltData);
                    sessionStorage.setItem(
                      "Tz_End",
                      JSON.stringify(JSON.parse(res.data.RltData))
                    );
                  } else {
                    this.user.Tz_End = {};
                    sessionStorage.setItem(
                      "Tz_End",
                      JSON.stringify(this.user.Tz_End)
                    );
                    // ElMessage.error("获取数据失败，请重试。");
                  }
                    this.$router.replace("/souye");
                    this.stopScanning();
                })
                .catch((error) => {
                   Quagga.start()
                  // console.log(error);
                  // ElMessage.error("网络不稳定,请联系工作人员");
                });
            } else {
              // ElMessage.error("扫描失败，请重试。");
              Quagga.start(); // 重新开始扫描
            }
          })
          .catch((error) => {
            // console.log(error);
            // ElMessage.error("网络不稳定,请联系工作人员");
            Quagga.start(); // 重新开始扫描
          });
      }
    },
    stopScanning() {
      Quagga.stop();
    }
  },
  beforeDestroy() {
    this.stopScanning();
  }
};
</script>

<style scoped>
.scaner {
  position: fixed;
  width: 100%;
  height: 100%;
  height: -webkit-calc(100%);
  height: -moz-calc(100%);
  height: -ms-calc(100%);
  height: -o-calc(100%);
  height: calc(100%);
}
#canvas {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  /* transform: translate(-50%,-50%); */
}
#video {
  width: 100%;
  height: 100%;
  /* top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed; */
}
.scaner .banner {
  width: 100%;
  position: absolute;
  top: 16px;
  left: 50%;
  margin-left: -170px;
  background: #fa74a2;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 12px;
  opacity: 0.9;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
}
.scaner .banner .text {
  padding: 0;
  margin: 0;
  color: #ffffff;
  font-size: 12px;
  text-align: justify;
  text-align-last: left;
}
.scaner .banner .close_icon {
  display: inline-block;
  height: 24px;
  width: 24px;
  background: url("../assets/close.png") no-repeat center;
  background-size: auto 100%;
  position: absolute;
  right: 8px;
  top: 8px;
}
.scaner .cover {
  height: 110px;
  width: 220px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0.5px solid #999999;
  z-index: 1111;
}
.scaner .cover .line {
  width: 200px;
  height: 1px;
  margin-left: 10px;
  background: #5f68e8;
  background: linear-gradient(
    to right,
    transparent,
    #5f68e8,
    #0165ff,
    #5f68e8,
    transparent
  );
  position: absolute;
  -webkit-animation: scan 1.75s infinite linear;
  -moz-animation: scan 1.75s infinite linear;
  -ms-animation: scan 1.75s infinite linear;
  -o-animation: scan 1.75s infinite linear;
  animation: scan 1.75s infinite linear;
  -webkit-animation-fill-mode: both;
  -moz-animation-fill-mode: both;
  -ms-animation-fill-mode: both;
  -o-animation-fill-mode: both;
  animation-fill-mode: both;
  border-radius: 1px;
}
.scaner .cover .square {
  display: inline-block;
  height: 20px;
  width: 20px;
  position: absolute;
}
.scaner .cover .square.top {
  top: 0;
  border-top: 1px solid #5f68e8;
}
.scaner .cover .square.left {
  left: 0;
  border-left: 1px solid #5f68e8;
}
.scaner .cover .square.bottom {
  bottom: 0;
  border-bottom: 1px solid #5f68e8;
}
.scaner .cover .square.right {
  right: 0;
  border-right: 1px solid #5f68e8;
}
.scaner .cover .tips {
  position: absolute;
  bottom: -48px;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
  opacity: 0.8;
}
@-webkit-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-moz-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-o-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
</style>